package com.zhentao.equipment.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.equipment.mapper.DeviceStatusLogMapper;
import com.zhentao.pojo.DeviceStatusLog;
import com.zhentao.util.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * 在线状态与状态日志服务
 */
@Service
public class DeviceStatusService {

    @Autowired(required = false)
    private StringRedisTemplate redis;

    @Autowired
    private DeviceStatusLogMapper logMapper;

    private String onlineKey(Long deviceId) { return "device:online:" + deviceId; }

    /** 查询是否在线（心跳时间在阈值内） */
    public ResultVo online(Long deviceId, long timeoutMillis) {
        if (redis == null) return ResultVo.success(false);
        String ts = redis.opsForValue().get(onlineKey(deviceId));
        if (ts == null) return ResultVo.success(false);
        long last = Long.parseLong(ts);
        boolean online = System.currentTimeMillis() - last <= timeoutMillis;
        return ResultVo.success(online);
    }

    /** 分页查询状态变更日志 */
    public ResultVo logs(Long deviceId, Integer pageNum, Integer pageSize) {
        Page<DeviceStatusLog> page = new Page<>(pageNum == null ? 1 : pageNum, pageSize == null ? 10 : pageSize);
        LambdaQueryWrapper<DeviceStatusLog> qw = new LambdaQueryWrapper<DeviceStatusLog>()
                .eq(DeviceStatusLog::getDeviceId, deviceId)
                .orderByDesc(DeviceStatusLog::getCreateTime);
        return ResultVo.success(logMapper.selectPage(page, qw));
    }
}





